<template>
  <BasicModal
    v-bind="$attrs"
    :width="modalWidth"
    @register="registerModal"
    :title="getTitle"
    @ok="handleOK"
  >
    <div style="display: flex">
      <Card
        :tab-list="tabListTitle"
        v-bind="$attrs"
        :active-tab-key="activeKey"
        @tab-change="onTabChange"
      >
        <BasicForm @register="registerForm" v-if="activeKey == t('sys.informaionMatchaing.columns.match')" />

        <BasicForm @register="registerFormpositon" v-if="activeKey == t('sys.informaionMatchaing.columns.orientation')">
          <template #colSlot_field5="{ model, field, disabled }">
            <FormItem
              :name="field"
              label="关键字"
              :rules="[{ required: true }]"
              :labelCol="{ span: 5 }"
            >
              <a-input v-model:value="model[field]" :disabled="disabled" placeholder="关键字" />
            </FormItem>
          </template>
        </BasicForm>
        <div v-if="activeKey == t('sys.informaionMatchaing.columns.orientation')">
          <Button
            type="primary"
            style="margin-left: 30px; margin-top: 10px"
            @click="onSearch('keyword')"
            >生成关键字</Button
          >

          <Button type="primary" style="margin-left: 30px; margin-top: 5px" @click="onSearch"
            >生成提示词</Button
          >

          <div v-if="tips">
            <div style="margin: 10px 0 0 10px; font-weight: bold">提示词</div>
            <div style="margin-left: 20px; margin-top: 10px">
              <a-textarea v-model:value="tips" :autoSize="{ minRows: 5, maxRows: 10 }" />
            </div>
          </div>
        </div>
      </Card>

      <div style="width: 100%" v-if="(keywordObject.length > 0 || tips) && activeKey == t('sys.informaionMatchaing.columns.orientation')">
        <div v-if="keywordObject.length > 0">
          <span style="margin-left: 10px; font-weight: bold">关键字</span>
          <div style="margin-left: 20px">
            <div
              v-for="(item, index) in keywordObject"
              :key="index"
              style="margin-top: 10px; display: flex"
            >
              <a-input v-model:value="item.keyword" placeholder="关键字" />

              <div style="margin: 0 20px">
                <InputNumber
                  id="inputNumber"
                  autofocus
                  v-model:value="item.score"
                  :min="0"
                  :max="1"
                  :step="0.1"
                  placeholder="权重"
                />
              </div>

              <Icon
                icon="ant-design:close-circle-outlined"
                @click="delkeyWord(index)"
                :size="30"
                v-if="index != keywordObject.length - 1"
                style="margin-left: 5px"
              />
              <Icon
                icon="ant-design:plus-circle-outlined"
                @click="addkeyWord"
                :size="30"
                v-if="index == keywordObject.length - 1"
                style="margin-left: 5px"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { onMounted, watch } from 'vue';
  import { Steps, Card, FormItem, Button, message, InputNumber } from 'ant-design-vue';
  import Icon from '@/components/Icon/Icon.vue';
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import axios from 'axios';
  import { matchCategory } from '@/api/demo/InformationMatching'; // 假设 matchCategory 接口在这里
  import { accountFormSchema, accountFormSchemPeople } from './account.data';
  import { AddTaskpageListAPI, categorAPI } from '@/api/demo/InformationMatching';
  import AButton from '@/components/VxeTable/src/components/AButton';
  import { getlistMatchOrientationTemplateAPI } from '@/api/demo/template';
  import { useI18n } from "@/hooks/web/useI18n";

  const { t } = useI18n();
  const MatchingType = ref([]);
  const accountFormSchemapositon = computed(() => [
    {
      field: 'template',
      component: 'ApiSelect',
      label: '选择模板',
      colProps: {
        span: 24,
      },
      defaultValue: null,
      componentProps: {
        resultField: 'data', // 指定返回数据中的数组字段
        api: getlistMatchOrientationTemplateAPI,
        labelField: 'remark',
        valueField: 'id',
        placeholder: '请选择模板', // 添加提示文本
      },
    },
    {
      field: 'title',
      component: 'Input',
      label: t('sys.informaionMatchaing.columns.title'),
      defaultValue: '',
      colProps: {
        span: 24,
      },
      rules: [{ required: true }],
    },
    {
      field: 'remark',
      component: 'InputTextArea',
      label: t('sys.configuration.describe'),
      defaultValue: '',
      colProps: {
        span: 24,
      },
      componentProps: {
        rows: 3, // 设置文本域的行数
      },
      rules: [{ required: true }],
    },
    {
      field: 'category',
      component: 'AutoComplete',
      label: t('sys.informaionMatchaing.columns.category'),
      defaultValue: '',
      colProps: {
        span: 24,
      },
      componentProps: {
        options: MatchingType,
        filterOption: (inputValue, option) => {
          return option.value.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1;
        },
        onChange: (value) => {
          // 这里是你想要执行的方法
          handleCategoryChange(value);
        },
      },
      rules: [{ required: true }],
    },
    {
      field: 'date',
      component: 'DatePicker',
      label: t('sys.informaionMatchaing.columns.DatePicker'),
      defaultValue: '',
      colProps: {
        span: 24,
      },
      componentProps: {
        format: 'YYYY-MM-DD HH:mm:ss', // 设置显示格式
        showTime: true, // 显示时间选择器
        valueFormat: 'YYYY-MM-DD HH:mm:ss', // 设置返回值的格式
      },
      rules: [{ required: true }],
    },
    {
      field: 'maxNum',
      component: 'Input',
      label: t('sys.orientation.maxNum'),
      /**!!!renderColContent 没有FormItem 包裹, 若想要 Form 提交需要带上数据须 <FormItem name={}></FormItem> 包裹： 示例如下*/
      colProps: {
        span: 24,
      },
    },
    {
      field: 'maxNode',
      component: 'Input',
      label: t('sys.orientation.maxNode'),
      /**!!!renderColContent 没有FormItem 包裹, 若想要 Form 提交需要带上数据须 <FormItem name={}></FormItem> 包裹： 示例如下*/
      colProps: {
        span: 24,
      },
    },
    {
      field: 'target',
      component: 'Input',
      label: '目标人群',
      /**!!!renderColContent 没有FormItem 包裹, 若想要 Form 提交需要带上数据须 <FormItem name={}></FormItem> 包裹： 示例如下*/
      colProps: {
        span: 24,
      },
    },
  ]);
  const emit = defineEmits(['success']);
  defineOptions({ name: 'AccountModal' });
  const isUpdate = ref(true);
  const rowId = ref('');
  const modalWidth = ref('50%');
  const activeKey = ref(t('sys.informaionMatchaing.columns.match'));
  const KeyWord = ref<string[]>([]);
  const tips = ref('');
  const tabListTitle = [
    {
      key: t('sys.informaionMatchaing.columns.match'),
      tab: t('sys.informaionMatchaing.columns.match'),
    },
    {
      key: t('sys.informaionMatchaing.columns.orientation'),
      tab: t('sys.informaionMatchaing.columns.orientation'),
    },
  ];
  const keyList = ref<{ content: string }[]>([{ content: '' }]); // 默认有一个目标方向
  const [registerForm, { resetFields, setFieldsValue, updateSchema, getFieldsValue }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: accountFormSchema,
    showActionButtonGroup: false,
  });
  //定向匹配
  const [
    registerFormpositon,
    { getFieldsValue: getFieldsValuePosi, updateSchema: updateSchemaPo },
  ] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: accountFormSchemapositon,
    showActionButtonGroup: false,
  });

  //人员匹配

  const [registerFormPeople] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: accountFormSchemPeople,
    showActionButtonGroup: false,
  });
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      setFieldsValue({
        ...data.record,
      });
    }

    const categoryData = await matchCategory();
    // 更新 accountFormSchema 中的 MatchingType 值
    updateSchema({
      field: 'category',
      componentProps: { options: categoryData.data },
    });

    updateSchemaPo({
      field: 'category',
      componentProps: { options: categoryData.data },
    });
  });
  const getTitle = computed(() => (!unref(isUpdate) ? t('sys.configuration.add') : t('sys.configuration.edit')));
  async function handleCategoryChange(value: string) {
    let Data = await categorAPI(value);
    // Data.data.forEach((item) => {
    //   keywordObject.value.push(item);
    // });
    //直接赋值
    keywordObject.value = Data.data;

    keywordObject.value.sort((a, b) => b.score - a.score);
  }
  async function handleOK() {
    setModalProps({ confirmLoading: true }); // 设置加载状态

    let params = {};

    if (activeKey.value == t('sys.informaionMatchaing.columns.match')) {
      params = { ...getFieldsValue(), type: 'match' };
      const data = await AddTaskpageListAPI(params);
      emit('success', data); // 触发 success 事件
      closeModal();
    } else {
      if (keywordObject.value.length > 0) {
        if (tips.value) {
          const keyWordString = keywordObject.value.map((ele) => {
            return `${ele.keyword}:${ele.score}`;
          });

          params = {
            ...getFieldsValuePosi(),
            keyWord: keyWordString.join(','),
            type: 'orientation',
            callword: tips.value,
          };
          const data = await AddTaskpageListAPI(params);
          emit('success', data); // 触发 success 事件
          closeModal();
        } else {
          message.error('请先生成提示词');
        }
      } else {
        message.error('请先生成关键字');
      }
    }

    await resetFields(); // 清除表单数据
    setModalProps({ confirmLoading: false }); // 关闭加载状态
  }
  async function onTabChange(key) {
    activeKey.value = key;
    const categoryData = await matchCategory();
    // 更新 accountFormSchema 中的 MatchingType 值
    updateSchema({
      field: 'category',
      componentProps: { options: categoryData.data },
    });

    updateSchemaPo({
      field: 'category',
      componentProps: { options: categoryData.data },
    });
  }
  function add() {
    keyList.value.push({ content: '' });
  }

  function del(index: number) {
    keyList.value.splice(index, 1);
  }
  function delkeyWord(index: number) {
    keywordObject.value.splice(index, 1);
  }

  function addkeyWord() {
    keywordObject.value.push('');
  }
  const keywordObject = ref<{ keyword: string; score: number }[]>([]);
  async function fetchKeywords(params) {
    //本地 http://192.168.0.109:6001
    //线上 http://8.136.118.105:6001
    try {
      const response = await axios.get('http://8.136.118.105:6001/getWords', {
        params,
      });

      if (response.data.data != 'None') {
        KeyWord.value = response.data.data.split(',');
      }
      keywordObject.value = KeyWord.value.map((keyword) => ({
        keyword: keyword,
        score: 0,
      }));
      return response.data;
    } catch (error) {
      message.error('生成关键字失败');
      return null;
    }
  }

  async function fetchKeytips(params) {
    //本地 http://192.168.0.109:6001
    //线上 http://8.136.118.105:6001
    try {
      const response = await axios.get('http://8.136.118.105:6001/getTips', {
        params,
      });

      tips.value = response.data.data;

      return response.data;
    } catch (error) {
      message.error('生成提示词');
      return null;
    }
  }

  async function onSearch(value) {
    if (keyList.value.length == 0) {
      message.error('请输入目标方向,生成有效关键字');
    } else {
      KeyWord.value = []; // 清空数据
      let Data = { ...getFieldsValuePosi() };
      let keyListValue = keyList.value.map((item) => item.content).join(',');

      if (value == 'keyword') {
        let params = {
          content: Data.remark,
          keyList: keyListValue,
        };
        const data = await fetchKeywords(params);
        if (data) {
          message.success('生成关键字成功');
        }
      } else {
        let params = {
          content: Data.remark,
          title: Data.title,
          target: Data.target,
        };
        const data = await fetchKeytips(params);
        if (data) {
          message.success('生成提示词成功');
        }
      }
    }
  }

  async function onSubmit() {
    if (tips.value.trim() === '') {
      message.error('提示词不能为空');
      return;
    }
    let Data = { ...getFieldsValuePosi() };
    let params = {
      tips: tips.value,
      content: Data.remark,
    };
    const data = await fetchKeywords(params);
    if (data) {
      message.success(t('sys.configuration.succesSubmit'));
    } else {
      message.error('提交失败');
    }
  }
</script>
